package com.javamis.modular.demo.service.impl;

import static com.javamis.config.shiro.ShiroUtils.getShiroInfo;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javamis.common.message.Message;
import com.javamis.common.util.JsonTransferUtils;
import com.javamis.common.util.UUIDUtils;
import com.javamis.config.shiro.ShiroInfo;
import com.javamis.modular.demo.dao.AssStorageMapper;
import com.javamis.modular.demo.service.AssStorageService;
import com.javamis.modular.flowable.dao.FlowableModelMapper;
import com.javamis.modular.flowable.dao.FlowableOfficeMapper;
import com.javamis.modular.flowable.entity.FlowFormBusiness;
import com.javamis.modular.flowable.entity.Flowable;
import com.javamis.modular.flowable.entity.FlowableMisModelForm;
import com.javamis.modular.flowable.entity.flowable.FlowableCompleteTask;
import com.javamis.modular.flowable.entity.flowable.FlowableStartProcessInstance;
import com.javamis.modular.flowable.service.FlowTaskService;
import com.javamis.modular.flowable.service.IFlowableProcessInstanceService;
import com.javamis.modular.flowable.service.IFlowableTaskService;
import com.javamis.modular.demo.entity.AssStorage;

/**
 * @name:   固定资产类接口实现类
 * @version:1.0.2
 * @author:	HuiJia
 * @QQ号： 	763236277
 * @QQ群： 	327773608
 * @邮箱: 	javamis@163.com
 * @site：	http://www.javamis.com
 */
@Service
public class AssStorageServiceImpl extends ServiceImpl<AssStorageMapper, AssStorage> implements AssStorageService  {
	@Autowired
    private FlowableOfficeMapper flowableOfficeMapper;
	@Autowired
	private FlowTaskService actTaskService;
	@Autowired
	private FlowTaskService flowTaskService;
	@Autowired
    private RepositoryService repositoryService;
	@Autowired
    private IFlowableProcessInstanceService iFlowableProcessInstanceService;
	@Autowired
	private FlowableModelMapper flowableModelMapper;
	@Autowired
    private IFlowableTaskService iFlowableTaskService;
	
	@Override
	public List<AssStorage> listData(List<AssStorage> assStorageLists) {
		List<AssStorage> assStoragesWarp = new ArrayList<AssStorage>();
   	 for(AssStorage as: assStorageLists) {
   		 FlowableMisModelForm misModelForm = flowableOfficeMapper.selectByBusinessTableId(as.getId());
    		 if(misModelForm != null) {
	     		 as.setProcDefId(misModelForm.getProcessDefinitionId());
	     		 as.setProcInsId(misModelForm.getProcessInstanceId());
	     		 
	     		if(flowTaskService.getHistoryProcIns(misModelForm.getProcessInstanceId()).getEndActivityId()!=null) {
	     			 as.setProcessIsFinished("10002");//已完结(该流程已走完所有流程的审批过程，该流程已关闭)
	     		 } else {
	 				as.setProcessIsFinished("10001");//审核中(该流程正在审核过程中)
	     		 }
    		 }
    		 assStoragesWarp.add(as);
    	 }
		return assStoragesWarp;
	}

	@Override
	public Message<String> save(AssStorage assStorage, Flowable flowable) {
		ShiroInfo shiroInfo = getShiroInfo();
   	 	String loginCode =shiroInfo.getUserCode();
    	
        // 初次-发起流程
        if (StringUtils.isBlank(flowable.getBusinessId())) {
        	//String modelKey = "zcgl-key";
        	//String modelKey = "leave-2020";//模型key
        	String modelKey = "zcdj";//模型key
        	ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey(modelKey).latestVersion().singleResult();
        	flowable.setFormId(assStorage.getId());
            FlowFormBusiness formBusiness = new FlowFormBusiness(flowable.getFormId());
            formBusiness.preInsert();
            
            /**
             * 1、设置变量
             * 1.1、设置提交人字段为空字符串让其自动跳过
             * 1.2、设置可以自动跳过
             * 1.3、汇报线的参数设置
             */
            String procIns="";
            Map<String, Object> variables1 = new LinkedHashMap<>();
            try {
            	FlowableStartProcessInstance spiv = new FlowableStartProcessInstance();
            	spiv.setProcessDefinitionKey(modelKey);
            	spiv.setBusinessKey(UUIDUtils.counter());
            	
            	String leaveId = UUIDUtils.counter();
                FlowableStartProcessInstance flowableStartProcessInstance = new FlowableStartProcessInstance();
                flowableStartProcessInstance.setBusinessKey(leaveId);
                flowableStartProcessInstance.setCreator(loginCode);
                flowableStartProcessInstance.setCurrentUserCode(loginCode);
                flowableStartProcessInstance.setFormName("资产登记流程");
                flowableStartProcessInstance.setProcessDefinitionKey(modelKey);
                flowableStartProcessInstance.setProcessDefinition(processDefinition);
                
                variables1=initAssStorageVariables(assStorage);
                flowableStartProcessInstance.setVariables(variables1);
                Message<ProcessInstance> returnStart = iFlowableProcessInstanceService.startProcessInstanceByKey(flowableStartProcessInstance);
                if (returnStart.getCode() == 100){
                	procIns = returnStart.getData().getProcessInstanceId();
                }
            }catch(Exception e) {
            	return Message.error(500, " 流程key： "+modelKey+" 的流程以被 '挂起', 请联系管理人员恢复该工作流程! ");
            }
            formBusiness.setProcInsId(procIns);
            assStorage.setProcessInstanceId(procIns);
            String relationUrl = flowableModelMapper.selectImsModelByModelKey(modelKey).getFormUrl();//url数据来源于模型关联表单
            String formUrl = relationUrl+"/"+assStorage.getId()+"?";
            Map<String,Object> map = JsonTransferUtils.keyReversalValueMap(variables1);
            if(flowableOfficeMapper.insertImsFlowRelationTable(UUIDUtils.counter(),assStorage.getId(),processDefinition.getId(),procIns,modelKey,formUrl,new Date(),JsonTransferUtils.mapConvertToJson(variables1),JsonTransferUtils.mapConvertToJson(map))>0) {
            	System.out.println("流程实例ID： "+procIns);
            	//return Message.success("流程启动成功啦!");
            	Message.success("添加流程表单成功啦!");
            }else {
            	return Message.success("流程启动失败!");
            }
        }
        //提交流程-end
		return Message.success("添加流程表单成功啦!");
	}
	
	/**
	 * 初始化流程参数
	 * @author:HuiJia
	 * @param obj
	 * @return
	 */
	public Map<String, Object> initAssStorageVariables(AssStorage assStorage){
		//获取参数,设置参数对象
		Map<String, Object> variables = new LinkedHashMap<String, Object>();
		
		//相关参数-------------->张三
		variables.put("zhangsan", "003");
		
		//相关参数-------------->李四
		variables.put("lisi", "004");
				
		//相关参数-------------->王五
		variables.put("wangwu", "005");
		
		//相关参数-------------->赵六		
		variables.put("zhaoliu", "006");
		
		//相关参数-------------->陈七
		variables.put("chenqi", "007");
		
		//相关参数-------------->谢八
		variables.put("xieba", "008");
		
		
		//相关参数-------------->金额<=10000 直接出纳审批，金额>10000总经理审批完成后再到出纳
		variables.put("amount", assStorage.getAmount());
		System.out.println("variables-------------------->" + variables);
		return variables;
	}

	@Override
	public Flowable edit(Flowable flowable) {
		// 获取流程实例对象
		if (flowable.getProcInsId() != null && !flowable.getStatus().equals("lookup")) {
			ProcessInstance procIns = actTaskService.getProcIns(flowable.getProcInsId());// 非发起流程
			if(procIns!=null) {
				flowable.setBusinessId(procIns.getBusinessKey());
				System.out.println("编辑时的-BusinessId: "+flowable.getBusinessId());
			}else {
				HistoricProcessInstance history = actTaskService.getHistoryProcIns(flowable.getProcInsId());
				flowable.setBusinessId(history.getBusinessKey());
				System.out.println("编辑时的-BusinessId: "+flowable.getBusinessId());
			}
			System.out.println("编辑时的-TaskId: "+flowable.getTaskId());
			System.out.println("编辑时的-ProcInsId: "+flowable.getProcInsId());
			flowable.setHasUnAuditPassFlow(false);
		}
		return flowable;
	}

	@Override
	public void edit(AssStorage assStorage, Flowable flowable) {
		//审批
		if(assStorage.getIsAgree() == 1) {        	
        	FlowableCompleteTask flowableCompleteTask = new FlowableCompleteTask();
        	flowableCompleteTask.setTaskId(flowable.getTaskId());
        	flowableCompleteTask.setUserCode(getShiroInfo().getUserCode());//当前登录人
        	flowableCompleteTask.setMessage(flowable.getComment());
        	flowableCompleteTask.setProcessInstanceId(flowable.getProcInsId());
        	flowableCompleteTask.setType("SP");
        	iFlowableTaskService.complete(flowableCompleteTask);
		}
	}
}
